﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using Kaixin.Components.Master.DTO;

namespace Kaixin.Components.Master.DAL
{
    class SettingXML
    {
        private readonly string _path = AppDomain.CurrentDomain.BaseDirectory + "MasterSetting.xml";

        private XDocument _xd;

        public SettingXML()
        {
            if (File.Exists(_path))
            {
                _xd = XDocument.Load(_path);
            }
            else
            {
                XElement root = new XElement("root");
                root.SetAttributeValue("Version", "1.0");
                _xd = new XDocument(root);
                _xd.Save(_path);
            }
        }

        public void SetSetting(Setting set)
        {
            var user = _xd.Document.Elements("user").Where(el => el.Element("email").Value == set.Email).FirstOrDefault();
            if (user == null)
            {
                AddSetting(set);
            }
            else
            {
                UpdateSetting(set,user);
            }
            _xd.Save(_path);
        }

        public void InitSetting(Setting set)
        {
            var user = _xd.Document.Elements("user").Where(el => el.Element("email").Value == set.Email).FirstOrDefault();
            if (user!=null)
            {
                set.NextPKTime = DateTime.Parse(user.Element("next").Value);
            }
        }

        private void AddSetting(Setting set)
        {
            _xd.Document.Element("root").Add(new XElement("user",
                new XElement("email", set.Email),
                new XElement("next", set.NextPKTime)));
        }

        private void UpdateSetting(Setting set, XElement el)
        {
            el.Element("next").Value = set.NextPKTime.ToString();
        }
    }
}
